package com.tianguxx.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;

public class DownloaderService extends Service {

	String src = "/sdcard/";
	String fileName = "data.xml";
	String path = "http://www.interbobo.com/mobile/data.xml";

	@Override
	public void onCreate() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			download(DownloaderService.this, path, src, fileName);
		}
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	public static void download(final Context context, final String path,
			final String src, final String fileName) {
		new Thread(new Runnable() {

			private int size;

			public void run() {

				try {
					if (path != null) {
						URL sourceUrl = new URL(path);
						HttpURLConnection conn = (HttpURLConnection) sourceUrl
								.openConnection();

						if (conn.getResponseCode() == 200) {
							File savePath = new File(src);
							if (!savePath.exists()) {
								savePath.mkdirs();
							}
							File saveFile = new File(savePath + "/" + fileName);
							if (saveFile.exists()) {
								saveFile.delete();
								saveFile.createNewFile();
							} else {
								saveFile.createNewFile();
							}
							int fileSize = conn.getContentLength();
							InputStream inputStream = conn.getInputStream();
							FileOutputStream fos = new FileOutputStream(
									saveFile);
							byte buf[] = new byte[1024];
							do {
								int numread = inputStream.read(buf);
								if (numread <= 0) {
									break;
								}
								size += numread;
								fos.write(buf, 0, numread);

							} while (true);
							inputStream.close();
							fos.close();
							int size = (int) saveFile.length();
							if (size == fileSize) {

							}

						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}).start();
	}

}
